import time
from PyQt5.Qt import *
from PIL import Image, ImageQt, ImageGrab
from io import BytesIO
import sys
import math
import pyautogui as pag
from pywinauto.application import Application
import pyaudio
import numpy as np
import random

app = Application(backend="uia").connect(title='魔兽世界', timeout=10)
main_window = app.window(title='魔兽世界')
p = pyaudio.PyAudio()


class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("出发吧钓鱼仔~")
        self.resize(322, 380)
        self.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.setup_ui()

    def setup_ui(self):
        self.btn_getImg = QPushButton("寻找浮漂", self)
        self.btn_getImg.resize(60, 30)
        self.btn_getImg.move(70, 10)

        self.btn_fishing = QPushButton("下竿", self)
        self.btn_fishing.resize(60, 30)
        self.btn_fishing.move(10, 10)

        self.auto_fishing = QPushButton("自动钓鱼", self)
        self.auto_fishing.resize(60, 30)
        self.auto_fishing.move(130, 10)

        self.label_img = QLabel(self)
        self.label_img.resize(300, 300)
        self.label_img.move(11, 40)
        self.label_img.setStyleSheet("border:1px solid gray")

        self.label_point = QLabel("坐标:", self)
        self.label_point.move(10, 350)


array_all = []


def get_image():
    global array_all
    array_all = []

    img_area = ImageGrab.grab(bbox=(700, 200, 1200, 600))

    width = img_area.size[0]
    height = img_area.size[1]
    print(width, height)
    for x in range(width):
        for y in range(height):
            r, g, b = img_area.getpixel((x, y))
            # print(r, g, b)
            if r > 128 and r < 168 and g > 33 and g < 73 and b > 28 and b < 68:
                img_area.putpixel((x, y), (0, 255, 0))
                array_all.append([x, y])

    if img_area.mode != 'RGBA':
        img_area = img_area.convert('RGBA')
    q_img_bytes = BytesIO()
    img_area.save(q_img_bytes, format='PNG')  # PNG 支持透明度
    q_img = QImage()
    q_img.loadFromData(q_img_bytes.getvalue(), 'PNG')
    # 将 QImage 转换为 QPixmap
    pixmap = QPixmap.fromImage(q_img)

    # 缩放 QPixmap 以适应 QLabel 的大小（保持宽高比）
    # 注意：这里我们假设 window.label_img 已经有一个有效的大小
    pixmap = pixmap.scaled(window.label_img.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)

    # 设置 QLabel 的 pixmap
    window.label_img.setPixmap(pixmap)

    point = get_max_point(array_all)
    if point == [10, 10, 10]:
        print("未发现")
    else:
        window.label_point.setText(f"坐标: {str(point[0])} {str(point[1])}")
        window.label_point.adjustSize()

        # moveto
        point_x = point[0] + 702
        point_y = point[1] + 200

        main_window.set_focus()
        pag.moveTo(point_x, point_y, random.uniform(0.2, 1))
        # time.sleep(0.2)
        # pag.rightClick()


def get_max_point(arr_all):  #
    arr_group = [[0, 0, 2]]
    for item in arr_all:
        # pnint（"新数组",item）
        # print("已存在",arr_group)
        save_flag = False
        for scale in arr_group:
            if math.fabs(scale[0] - item[0]) < 50 and math.fabs(scale[1] - item[1]) < 50:
                print(scale[0], item[0])
                scale[0] = round(scale[0] + (item[0] - scale[0]) / scale[2], 2)
                print(scale[0])
                scale[1] = round(scale[1] + (item[1] - scale[1]) / scale[2], 2)
                scale[2] = scale[2] + 1
                save_flag = True
                continue
        if save_flag == False:
            arr_group.append([item[0], item[1], 2])
    # print(f"get -> {arr_group}")
    max_point = [10, 10, 10]
    for scale in arr_group:
        if scale[2] > max_point[2]:
            max_point[0] = round(scale[0])
            max_point[1] = round(scale[1])
            max_point[2] = round(scale[2])
    print(max_point)
    return max_point


def start_fish():
    main_window.set_focus()
    time.sleep(random.uniform(0.5, 1))
    pag.press('1')
    time.sleep(2)


def auto_fish():
    while True:
        start_fish()
        start_time = time.time()
        get_image()
        # 打开麦克风输入流
        stream = p.open(format=pyaudio.paInt16,
                        channels=1,
                        rate=44100,
                        input=True,
                        frames_per_buffer=1024)

        # 进行声音监听
        while True:

            # 从麦克风读取数据
            data = stream.read(1024)
            # 将读取的数据转换为数组（使用np.frombuffer代替np.fromstring）
            data = np.frombuffer(data, dtype=np.int16)

            # 在这里处理数据（例如，计算音量）
            total = np.sum(np.abs(data))  # 计算绝对值总和以模拟音量
            # print(total)
            end_time = time.time()
            if end_time - start_time > 15:
                print("Time out")
                break
            elif total >= 800000:
                time.sleep(random.uniform(0.2, 1.5))
                pag.rightClick()
                time.sleep(1)
                break
            else:
                continue


if __name__ == '__main__':
    app = QApplication(sys.argv)

    window = Window()
    window.btn_getImg.pressed.connect(get_image)
    window.btn_fishing.pressed.connect(start_fish)
    window.auto_fishing.pressed.connect(auto_fish)
    window.show()

    sys.exit(app.exec_())
